package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hqyj.dao.UserInfoMapper;
import com.hqyj.exception.CodeEnum;
import com.hqyj.exception.R;
import com.hqyj.pojo.UserInfo;
import com.hqyj.service.UserInfoService;
import com.hqyj.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    UserInfoMapper userInfoMapper;

    @Override
    public R login(UserInfo u) {
        /**
         * shiro的登录认证
         */
        //创建用户凭证
        UsernamePasswordToken token = new UsernamePasswordToken(u.getUserName(),u.getUserPwd());
        //创建shiro用户对象
        Subject subject = SecurityUtils.getSubject();
        try{
            //登录
            subject.login(token);
        }catch (UnknownAccountException e){
            log.info("用户名不正确");
            return R.error("用户名不正确");
        }catch (IncorrectCredentialsException e){
            log.info("密码不正确");
            return R.error("密码不正确");
        }
        log.info("登录成功");
        /*------------jwt认证，生成用户凭证------------*/
        //获取用户id
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",u.getUserName());
        String id  = userInfoMapper.selectOne(wrapper).getUserId();
        //生成jwt盐值
        String jwtSalt = UUID.randomUUID()+"";
        //生成token
        String tk = JwtUtil.createUserToken(id,u.getUserName(),jwtSalt);
        //返回用户token
        return R.ok("成功",tk);
    }
}
